import interceptors from './interceptors.js';
//判断是否http://或者https://的开发
let isProtocol = str => {
  let b = new RegExp('^http[s]?://')
  return b.test(str)
}
function abi(url, data){
  return abi.method({ url, data, method: 'GET'})
}
const config = [
  'get',
  'post',
  'put',
  'detele',
  'options',
  'head',
  'trace',
  'connect'
]
config.forEach( val => {
  abi[val] = (url, data) => abi.method( {url, data, method: val.toLocaleUpperCase()} )
})
abi.method = function ({ url, data, method, api = 'request'}){
  let res = typeof url === 'Object' ? url : { data, url };
  try {
    ({url, data} = this.interceptors.request.success(res))
    return new Promise((resolve, reject) => {
      let fnData = abi.unite({ url, data, method, resolve, reject });
      wx[api](fnData)
    });
  } catch(e) {
    return this.interceptors.request.error(res)
  }
}
abi.unite = function ({url, data, method, resolve, reject}){
  let fnData = {
    success: res => {
      let data = this.interceptors.response.success(res)
      resolve(data)
    },
    fail: res => {
      let data = this.interceptors.response.error(res)
      reject(data)
    }
  }
  fnData.method = method;
  if (typeof url === 'string') {
    fnData.url = this.pathMerge(url)
    fnData.data = data;
  } else if (typeof url === 'object') {
    url.url = this.pathMerge(url.url)
    Object.assign(fnData, url)
  }
  return fnData
}
abi.pathMerge = function(url){
  return isProtocol(url) ? url : this.defaults.baseURL + url
}
abi.defaults = {
  baseURL: '',
}
abi.interceptors = interceptors;
export default abi